package at.ac.tuwien.dse.health.mongodb;

import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfig;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

/**
 * Starts an embedded MongoDB instance.
 * <p/>
 * MongoDB listens on the specified port or uses the default MongoDBs default port {@code 27017} if none is defined.
 * <p/>
 * The default version is {@link de.flapdoodle.embed.mongo.distribution.Version.Main#DEVELOPMENT}, which is always the
 * latest version supported by {@link MongodExecutable}.
 *
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class EmbeddedMongoDB implements InitializingBean, DisposableBean {
	private static final Logger LOGGER = LogManager.getLogger(EmbeddedMongoDB.class);

	Version.Main version = Version.Main.DEVELOPMENT;
	int port = 27017;
	boolean started;
	MongodExecutable mongodExecutable;

	@Override
	public void afterPropertiesSet() throws IOException {
		MongodConfig mongodConfig = new MongodConfig(version, port, Network.localhostIsIPv6());
		MongodStarter runtime = MongodStarter.getDefaultInstance();
		MongodExecutable mongodExecutable = runtime.prepare(mongodConfig);
		try {
			mongodExecutable.start();
			started = true;
		} catch (IOException e) {
			LOGGER.warn("Cannot start embedded MongoDB. Please ensure that it is not already running.");
		}
	}

	@Override
	public void destroy() {
		if (mongodExecutable != null && started) {
			mongodExecutable.stop();
		}
	}

	public void setVersion(Version.Main version) {
		this.version = version;
	}

	public void setPort(int port) {
		this.port = port;
	}
}
